package com.web.portal.utils.file;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 图片上传工具类
 *
 * @author laiyingtao
 */
@Component
public class UploadImageUtil {
    //log日志
    private static final Logger logger = LoggerFactory.getLogger(UploadImageUtil.class);

    /**
     * 检查上传图像大小以及类型
     *
     * @param multipartFile   需要上传的图片
     * @param uploadImageBean 对图片的一些参数设置
     * @return
     */
    private static UploadImageResult checkUploadImage(MultipartFile multipartFile, UploadImageBean uploadImageBean) {
        UploadImageResult uploadImageResult = new UploadImageResult();
        uploadImageResult.setSuccess(false);
        String fileName = multipartFile.getOriginalFilename();
        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
        uploadImageResult.setFileName(fileName);
        uploadImageResult.setFileType(fileType);
        try {
            do {
                if (uploadImageBean != null) {
                    /*if (StringUtils.isEmpty(uploadImageBean.getEndPoint()) && StringUtils.isEmpty(uploadImageBean.getPath())) {
                        uploadImageResult.setMsg("请指定您的上传路径!");
                        break;
                    }
                    if (StringUtils.isEmpty(uploadImageBean.getFileType())) {
                        uploadImageResult.setMsg("请指定您的上传文件类型!");
                        break;
                    }
                    if (StringUtils.isEmpty(fileType)) {
                        uploadImageResult.setMsg("没有获取到您的上传文件所属类型!");
                        break;
                    }
                    if (!fileType.equals(uploadImageBean.getFileType())) {
                        uploadImageResult.setMsg("您上传的文件类型跟您指定的文件类型不匹配!");
                        break;
                    }*/
                    BufferedImage bi = ImageIO.read(multipartFile.getInputStream()); // 通过MultipartFile得到InputStream 得到BufferedImage
                    if (bi == null) {
                        uploadImageResult.setMsg("您上传的文件类型不是图片类型!");
                        break;
                    }
                    if (uploadImageBean.getWidth() != null && bi.getWidth() > uploadImageBean.getWidth()) {
                        uploadImageResult.setMsg("上传照片宽度不符合要求");
                        break;
                    }
                    if (uploadImageBean.getWidth() != null && bi.getHeight() > uploadImageBean.getHeight()) {
                        uploadImageResult.setMsg("上传照片高度不符合要求");
                        break;
                    }
                    if (uploadImageBean.getMaxSize() != null && !checkFileSize(multipartFile.getSize(), uploadImageBean.getMaxSize(), "M")) {
                        uploadImageResult.setMsg("上传照片过大");
                        break;
                    }
                }
                uploadImageResult.setSuccess(true);
                return uploadImageResult;
            }
            while (false);
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("上传图片,检查上传图像大小以及类型系统报错:【" + e + "】");
            uploadImageResult.setMsg(e.getMessage());
        }
        return uploadImageResult;
    }

    /**
     * 目标文件大小与理想文件大小的比较
     *
     * @param len
     * @param size
     * @param unit
     * @return
     */
    private static boolean checkFileSize(Long len, Long size, String unit) {
        double fileSize = 0;
        if ("B".equals(unit.toUpperCase())) {
            fileSize = (double) len;
        } else if ("K".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1024;
        } else if ("M".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1048576;
        } else if ("G".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1073741824;
        }
        if (fileSize > size) {
            return false;
        }
        return true;
    }

    /**
     * 上传图片成压缩图(PNG图片按JPG处理)
     *
     * @param multipartFile   需要上传的图片
     * @param uploadImageBean
     * @throws Exception
     */
    public static UploadImageResult uploadImageToCompress(MultipartFile multipartFile, UploadImageBean uploadImageBean) {
        //检查上传图像大小
        UploadImageResult uploadImageResult = checkUploadImage(multipartFile, uploadImageBean);
        if (!StringUtils.isEmpty(uploadImageResult.getMsg())) {
            return uploadImageResult;
        }
        try {
            //获取上传压缩图路径
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String compressPath = getUploadPath(multipartFile, uploadImageBean, "compress.", uuid);
            //存在该文件则删除,不存在则创建文件夹到该文件的上一级
            clear(compressPath);
            //压缩图上传
            ImageUtils.optimize(multipartFile.getInputStream(), new File(compressPath), uploadImageBean.getQuality());
            //返回图片路径给调用者
            uploadImageResult.setSuccess(true);
            uploadImageResult.setCompressImageUrl(compressPath);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("上传图片,上传图片成压缩图系统报错:【" + e + "】");
            uploadImageResult.setSuccess(false);
            uploadImageResult.setMsg(e.getMessage());
        }
        return uploadImageResult;
    }


    /**
     * 上传图片成压缩图(PNG图片按JPG处理) 和 缩略图
     *
     * @param multipartFile 需要上传的图片
     * @return
     */
    public static UploadImageResult uploadImageToCompressAndThumb(MultipartFile multipartFile, UploadImageBean uploadImageBean) {

        //检查上传图像大小
        UploadImageResult uploadImageResult = checkUploadImage(multipartFile, uploadImageBean);
        if (!StringUtils.isEmpty(uploadImageResult.getMsg())) {
            return uploadImageResult;
        }
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //获取压缩图上传路径
        String compressPath = getUploadPath(multipartFile, uploadImageBean, "compress.", uuid);
        //获取缩略图上传路径
        String thumbPath = getUploadPath(multipartFile, uploadImageBean, "thumb.", uuid);
        try {
            //存在该文件则删除,不存在则创建文件夹到该文件的上一级
            clear(compressPath);
            clear(thumbPath);
            //压缩图上传
            ImageUtils.optimize(multipartFile.getInputStream(), new File(compressPath), uploadImageBean.getQuality());
            //缩略图上传
            ImageUtils.resize(multipartFile.getInputStream(), new File(thumbPath),
                    uploadImageBean.getThumbWidth(), uploadImageBean.getThumbHeight(), uploadImageBean.getWidth().intValue(), uploadImageBean.getHeight().intValue());
            //返回图片路径给调用者
            uploadImageResult.setSuccess(true);
            uploadImageResult.setCompressImageUrl(compressPath);
            uploadImageResult.setThumbImageUrl(thumbPath);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("上传图片,上传图片成压缩图和缩略图系统报错:【" + e + "】");
            uploadImageResult.setSuccess(false);
            uploadImageResult.setMsg(e.getMessage());
        }
        return uploadImageResult;
    }

    /**
     * 上传图片成压缩图(PNG图片按JPG处理) 和 原图
     *
     * @param multipartFile 需要上传的图片
     * @return
     */
    public static UploadImageResult uploadImageToCompressAndOriginal(MultipartFile multipartFile, UploadImageBean uploadImageBean) {

        //检查上传图像大小
        UploadImageResult uploadImageResult = checkUploadImage(multipartFile, uploadImageBean);
        if (!StringUtils.isEmpty(uploadImageResult.getMsg())) {
            return uploadImageResult;
        }
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");

        //获取压缩图上传路径
        String compressPath = GlobalConst.FILE_UPLOAD_TOP + getUploadPath(multipartFile, uploadImageBean, "compress.",uuid);
        //获取原图上传路径
        String originalPath = GlobalConst.FILE_UPLOAD_TOP + getUploadPath(multipartFile, uploadImageBean, ".", uuid);
        try {
            //存在该文件则删除,不存在则创建文件夹到该文件的上一级
            //clear(compressPath);
            clear(originalPath);
            //压缩图上传
            ImageUtils.optimize(multipartFile.getInputStream(), new File(compressPath), 1f);
//            ImageUtils.uploadOriginalImage(multipartFile, compressPath, originalPath);
            //原来图上传
            ImageUtils.uploadOriginalImage(multipartFile, uploadImageBean.getPath(), originalPath);
            //返回图片路径给调用者
            uploadImageResult.setSuccess(true);
//            uploadImageResult.setCompressImageUrl(compressPath);
            originalPath = originalPath.replace(GlobalConst.FILE_UPLOAD_TOP, "");
            uploadImageResult.setOriginalImageUrl(originalPath);
            uploadImageResult.setCompressImageUrl(compressPath.replace(GlobalConst.FILE_UPLOAD_TOP, ""));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("文件上传报错。系统报错:【" + e + "】");
            uploadImageResult.setSuccess(false);
            uploadImageResult.setMsg(e.getMessage());
        }
        return uploadImageResult;
    }

    /**
     * 上传图片成压缩图(PNG图片按JPG处理) 和 原图
     *
     * @param multipartFile 需要上传的图片
     * @return
     */
    public static UploadImageResult uploadOtherFile(MultipartFile multipartFile, UploadImageBean uploadImageBean) {

        //检查上传图像大小
        UploadImageResult uploadImageResult = new UploadImageResult();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");

        //获取压缩图上传路径
        //String compressPath = getUploadPath(multipartFile, uploadImageBean, "compress.",uuid);
        //获取原图上传路径
        String originalPath = GlobalConst.FILE_UPLOAD_TOP + getUploadPath(multipartFile, uploadImageBean, ".", uuid);
        try {
            //存在该文件则删除,不存在则创建文件夹到该文件的上一级
            //clear(compressPath);
            clear(originalPath);
            //压缩图上传
            //ImageUtils.optimize(multipartFile.getInputStream(), new File(compressPath), uploadImageBean.getQuality());
            //原来图上传
            ImageUtils.uploadOriginalImage(multipartFile, uploadImageBean.getPath(), originalPath);
            //返回图片路径给调用者
            uploadImageResult.setSuccess(true);
//            uploadImageResult.setCompressImageUrl(compressPath);
            uploadImageResult.setOriginalImageUrl(originalPath.replace(GlobalConst.FILE_UPLOAD_TOP, ""));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("上传图片,上传图片成压缩图和原图系统报错:【" + e + "】");
            uploadImageResult.setSuccess(false);
            uploadImageResult.setMsg(e.getMessage());
        }
        return uploadImageResult;
    }


    /**
     * 上传图片成压缩图(PNG图片按JPG处理) 原图  和 缩略图
     *
     * @param multipartFile 需要上传的图片
     * @return
     */
    public static UploadImageResult uploadImageToCompressOriginalAndCompressThumb(MultipartFile multipartFile, UploadImageBean uploadImageBean) {

        //检查上传图像大小
        UploadImageResult uploadImageResult = checkUploadImage(multipartFile, uploadImageBean);
        if (!StringUtils.isEmpty(uploadImageResult.getMsg())) {
            return uploadImageResult;
        }
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //获取压缩图上传路径
        String compressPath = getUploadPath(multipartFile, uploadImageBean, "compress.", uuid);
        //获取缩略图上传路径
        String thumbPath = getUploadPath(multipartFile, uploadImageBean, "thumb.", uuid);
        //获取原图上传路径
        String originalPath = getUploadPath(multipartFile, uploadImageBean, ".", uuid);
        try {
            //存在该文件则删除,不存在则创建文件夹到该文件的上一级
            clear(compressPath);
            clear(originalPath);
            clear(thumbPath);
            //压缩图上传
            ImageUtils.optimize(multipartFile.getInputStream(), new File(compressPath), uploadImageBean.getQuality());
            //原来图上传
            ImageUtils.uploadOriginalImage(multipartFile, uploadImageBean.getPath(), originalPath);
            //缩略图上传
            ImageUtils.resize(multipartFile.getInputStream(), new File(thumbPath),
                    uploadImageBean.getThumbWidth(), uploadImageBean.getThumbHeight(), uploadImageBean.getWidth().intValue(), uploadImageBean.getHeight().intValue());
            //返回图片路径给调用者
            uploadImageResult.setSuccess(true);
            uploadImageResult.setCompressImageUrl(compressPath);
            uploadImageResult.setOriginalImageUrl(originalPath);
            uploadImageResult.setThumbImageUrl(thumbPath);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("上传图片,上传图片成压缩图原图和缩略图系统报错:【" + e + "】");
            uploadImageResult.setSuccess(false);
            uploadImageResult.setMsg(e.getMessage());
        }
        return uploadImageResult;
    }

    /**
     * 上传图片到阿里云服务器
     * @param multipartFile 需要上传的图片
     * @param reqUploadImageVo  对图片的一些参数设置
     * @return
     */
    /*
    public static void uploadImageToOSS(MultipartFile multipartFile, UploadImageBean uploadImageBean) {
    	// Endpoint以杭州为例，其它Region请按实际情况填写。
    	String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";
    	// 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
    	String accessKeyId = "LTAI4FiG5uDxeEQV3UETUPJm";
    	String accessKeySecret = "U8qCxRpD6znB5yCE4UFsVzv5YOwOTW";
    	// 创建OSSClient实例。
    	OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

    	// 创建PutObjectRequest对象。
    	//PutObjectRequest putObjectRequest = new PutObjectRequest("leeson-bucket", "12346", new File("F:\\img\\temp\\2019-05-27\\1558951496194_168x168.jpg"));
    	PutObjectRequest putObjectRequest = new PutObjectRequest("leeson-file", "12346", new File("F:\\img\\temp\\2019-05-27\\eSgsAlu3RNGACgrBAAQvXbkhrsQ177.jpg"));
    	// 如果需要上传时设置存储类型与访问权限，请参考以下示例代码。
    	// ObjectMetadata metadata = new ObjectMetadata();
    	// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
    	// metadata.setObjectAcl(CannedAccessControlList.Private);
    	// putObjectRequest.setMetadata(metadata);

    	// 上传文件。
    	PutObjectResult result = ossClient.putObject(putObjectRequest);
    	System.out.println(result);
//    	获取https链接
    	com.aliyun.oss.model.OSSObject ossObject = ossClient.getObject("leeson-file", "12346");
    	try {
    		// 关闭OSSClient。
	    	ossClient.shutdown();
			ossObject.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }*/

    /**
     * 获取上传路径
     *
     * @param multipartFile
     * @param suffix
     * @return
     */
    private static String getUploadPath(MultipartFile multipartFile, UploadImageBean uploadImageBean, String suffix, String uuid) {
        String uploadFileName = uuid + suffix +
                multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1, multipartFile.getOriginalFilename().length());//文件名称
        return uploadImageBean.getPath() + "/" + uploadFileName;
    }

    /**
     * 存在改文件则删除,不存在则创建文件夹到该文件的上一级
     *
     * @param path
     */
    private static void clear(String path) {
        File file = new File(path);
        if (file.isFile() && file.exists()) {
            file.delete();
        } else {
            FolderUtils.mkdirs(file.getParent());
        }
    }
}
